package org.springblade.core.license.listener;

import de.schlichtherle.license.LicenseContent;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.license.LicenseManagerHolder;
import org.springblade.core.tool.utils.SpringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Optional;


@Slf4j
@Component
@ConditionalOnProperty(value = "version.enable", havingValue = "true")
public class LicenseVerifyJob {

	/**
	 * 每1个小时检查一次
	 */
	@Scheduled(fixedRate =  600000,initialDelay = 300000)
	@PostConstruct
	public void verify() {
		Optional<LicenseContent> licenseContentOptional = LicenseManagerHolder.getLicenseContent();
		if (licenseContentOptional.isPresent()) {
			LicenseContent licenseContent = licenseContentOptional.get();
			// 证书过期
			if (licenseContent.getNotAfter().before(new Date())) {
				int exit = SpringApplication.exit(SpringUtil.getContext(), () -> 0);
				System.exit(exit);
			} else {
				log.info("vc success");
			}
		} else {
			log.info("vc error");
		}
	}

}
